<template>
  <div class="browse-history-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">浏览历史</h1>
    </div>

    <!-- 历史记录内容 -->
    <el-card class="history-card">
      <!-- 历史记录筛选和搜索 -->
      <div class="history-header">
        <div class="search-filter">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索浏览历史..."
            class="search-input"
            @keyup.enter="searchHistory"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="historyType" placeholder="选择类型" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="题目" value="question" />
            <el-option label="论坛帖子" value="forum" />
            <el-option label="学习资源" value="resource" />
            <el-option label="用户主页" value="user" />
          </el-select>
        </div>
        
        <div class="history-actions">
          <el-button type="primary" @click="clearAllHistory">
            <el-icon><Delete /></el-icon>
            清空历史
          </el-button>
          <el-button @click="batchDeleteHistory" :disabled="selectedHistory.length === 0">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 时间线历史记录 -->
      <div class="history-timeline" v-if="historyData.length > 0">
        <div v-for="(group, date) in groupedHistory" :key="date" class="history-group">
          <div class="history-date">
            <el-divider>{{ date }}</el-divider>
          </div>
          
          <div class="history-items">
            <el-table
              v-loading="loading"
              :data="group"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              
              <el-table-column prop="contentTitle" label="标题" width="400">
                <template #default="scope">
                  <div class="history-title">
                    <router-link :to="getHistoryLink(scope.row)" target="_blank">
                      {{ scope.row.contentTitle }}
                    </router-link>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column prop="contentType" label="类型" width="120">
                <template #default="scope">
                  <el-tag :type="getTagType(scope.row.contentType)">
                    {{ isArticleType(scope.row) ? '文章' : getTypeName(scope.row.contentType) }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="browseTime" label="浏览时间" width="180" />
              
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button type="text" @click="deleteSingleHistory(scope.row.id)">
                    删除
                  </el-button>
                  <el-button type="text" @click="viewHistory(scope.row)">
                    再次浏览
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 无历史记录提示 -->
      <div v-else-if="historyData.length === 0" class="empty-history">
        <div class="empty-content">
          <el-empty description="暂无浏览历史记录" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import { 
  getUserBrowseHistory, 
  getUserBrowseHistoryByType, 
  searchUserBrowseHistory,
  type BrowseHistoryItem,
  type BrowseHistoryResponse
} from '@/api/history'

// 路由
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const historyType = ref('all')
const loading = ref(false)
const selectedHistory = ref<BrowseHistoryItem[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalHistory = ref(0)

// 历史记录数据
const historyData = ref<BrowseHistoryItem[]>([])


// 加载浏览历史数据
const loadBrowseHistory = async () => {
  try {
    loading.value = true
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    
    console.log('开始加载浏览历史数据，用户ID:', userId)
    
    // 首先尝试从本地存储加载
    const historyKey = `browse_history_${userId}`
    const localHistory = JSON.parse(localStorage.getItem(historyKey) || '[]')
    console.log('本地存储的浏览历史数据:', localHistory)
    
    if (localHistory.length > 0) {
      console.log('使用本地存储的浏览历史数据:', localHistory.length)
      console.log('本地存储的原始数据:', localHistory)
      console.log('第一条记录的标题:', localHistory[0]?.contentTitle)
      historyData.value = localHistory
      totalHistory.value = localHistory.length
      
      // 同时尝试从API同步数据
      try {
        let response: BrowseHistoryResponse
        
        if (searchKeyword.value.trim()) {
          response = await searchUserBrowseHistory(Number(userId), searchKeyword.value.trim(), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else if (historyType.value !== 'all') {
          response = await getUserBrowseHistoryByType(Number(userId), historyType.value, {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else {
          response = await getUserBrowseHistory(Number(userId), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        }
        
        // 如果API成功，使用API数据
        if (response && response.content) {
          console.log('API数据加载成功，使用API数据')
          historyData.value = response.content
          totalHistory.value = response.totalElements
        }
      } catch (apiError) {
        console.log('API加载失败，继续使用本地数据:', apiError)
      }
    } else {
      // 本地没有数据，尝试从API加载
      try {
        let response: BrowseHistoryResponse
        
        if (searchKeyword.value.trim()) {
          response = await searchUserBrowseHistory(Number(userId), searchKeyword.value.trim(), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else if (historyType.value !== 'all') {
          response = await getUserBrowseHistoryByType(Number(userId), historyType.value, {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        } else {
          response = await getUserBrowseHistory(Number(userId), {
            page: currentPage.value - 1,
            size: pageSize.value
          })
        }
        
        historyData.value = response.content || []
        totalHistory.value = response.totalElements || 0
        console.log('API数据加载成功')
      } catch (apiError) {
        console.error('API加载失败:', apiError)
        historyData.value = []
        totalHistory.value = 0
        ElMessage.info('暂无浏览历史数据')
      }
    }
    
  } catch (error) {
    console.error('加载浏览历史失败:', error)
    historyData.value = []
    totalHistory.value = 0
    ElMessage.error('加载浏览历史失败')
  } finally {
    loading.value = false
  }
}

// 计算属性：根据搜索和筛选条件过滤历史记录
const groupedHistory = computed(() => {
  console.log('计算groupedHistory，当前historyData.value:', historyData.value)
  
  const filteredGroups: Record<string, BrowseHistoryItem[]> = {}
  
  // 先过滤数据
  let filteredData = historyData.value.filter(item => item && item.contentTitle && item.contentId)
  
  // 根据搜索关键词过滤
  if (searchKeyword.value.trim()) {
    filteredData = filteredData.filter(item => 
      item.contentTitle.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (item.contentDescription && item.contentDescription.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    )
  }
  
  // 根据类型过滤
  if (historyType.value !== 'all') {
    const typeMap: Record<string, string> = {
      'question': 'QUESTION',
      'forum': 'FORUM',
      'resource': 'RESOURCE',
      'article': 'ARTICLE',
      'user': 'USER'
    }
    const targetType = typeMap[historyType.value]
    if (targetType) {
      filteredData = filteredData.filter(item => {
        // 对于文章类型，需要特殊处理，因为文章使用FORUM类型但URL包含/article/
        if (targetType === 'ARTICLE') {
          return item.contentUrl && item.contentUrl.includes('/article/')
        }
        return item.contentType === targetType
      })
    }
  }
  
  console.log('过滤后的数据:', filteredData)
  
  // 将过滤后的数据按日期分组
  filteredData.forEach(item => {
    try {
      let date: string
      if (item.browseTime) {
        date = new Date(item.browseTime).toLocaleDateString('zh-CN')
      } else if (item.createdAt) {
        date = new Date(item.createdAt).toLocaleDateString('zh-CN')
      } else {
        date = new Date().toLocaleDateString('zh-CN')
      }
      
      if (!filteredGroups[date]) {
        filteredGroups[date] = []
      }
      filteredGroups[date].push(item)
    } catch (error) {
      console.error('日期解析错误:', error, 'item:', item)
      // 使用当前日期作为默认值
      const defaultDate = new Date().toLocaleDateString('zh-CN')
      if (!filteredGroups[defaultDate]) {
        filteredGroups[defaultDate] = []
      }
      filteredGroups[defaultDate].push(item)
    }
  })
  
  console.log('分组后的数据:', filteredGroups)
  console.log('分组后的数据类型:', typeof filteredGroups)
  console.log('分组后的数据键名:', Object.keys(filteredGroups))
  console.log('分组后的数据长度:', Object.keys(filteredGroups).length)
  return filteredGroups
})

// 获取历史记录类型的标签类型
const getTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'QUESTION': 'primary',
    'FORUM': 'success',
    'RESOURCE': 'warning',
    'ARTICLE': 'info',
    'USER': 'info'
  }
  return typeMap[type.toUpperCase()] || 'default'
}

// 获取历史记录类型的中文名称
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    'QUESTION': '题目',
    'FORUM': '论坛帖子',
    'RESOURCE': '学习资源',
    'ARTICLE': '文章',
    'USER': '用户主页'
  }
  return typeMap[type.toUpperCase()] || type
}

// 根据URL判断是否为文章类型
const isArticleType = (item: BrowseHistoryItem) => {
  return item.contentUrl && item.contentUrl.includes('/article/')
}

// 获取历史记录链接
const getHistoryLink = (item: BrowseHistoryItem) => {
  const linkMap: Record<string, string> = {
    QUESTION: `/search-question?id=${item.contentId}`,
    FORUM: `/forum/post/${item.contentId}`,
    RESOURCE: `/resources/detail/${item.contentId}`,
    ARTICLE: `/article/${item.contentId}`,
    USER: `/user/profile?id=${item.contentId}`
  }
  return linkMap[item.contentType] || '/'
}

// 搜索历史记录
const searchHistory = () => {
  console.log('搜索历史记录，关键词:', searchKeyword.value)
  // 搜索时重置选择
  selectedHistory.value = []
  // 重新加载数据
  loadBrowseHistory()
}

// 处理选择变化
const handleSelectionChange = (val: BrowseHistoryItem[]) => {
  selectedHistory.value = val
}

// 再次浏览
const viewHistory = (item: BrowseHistoryItem) => {
  const link = getHistoryLink(item)
  router.push(link)
}

// 删除单条历史记录
const deleteSingleHistory = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该浏览记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 从历史记录数组中删除
    const index = historyData.value.findIndex(item => item.id === id)
    if (index > -1) {
      historyData.value.splice(index, 1)
      totalHistory.value -= 1
      
      // 同步到本地存储
      const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
      const historyKey = `browse_history_${userId}`
      localStorage.setItem(historyKey, JSON.stringify(historyData.value))
    }
    
    ElMessage.success('浏览记录删除成功')
  } catch (error) {
    // 用户取消操作
  }
}

// 批量删除历史记录
const batchDeleteHistory = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHistory.value.length} 条浏览记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 删除选中的历史记录
    const selectedIds = selectedHistory.value.map(item => item.id)
    
    // 从历史记录数组中删除选中的记录
    selectedIds.forEach(id => {
      const index = historyData.value.findIndex(item => item.id === id)
      if (index > -1) {
        historyData.value.splice(index, 1)
        totalHistory.value -= 1
      }
    })
    
    // 同步到本地存储
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    const historyKey = `browse_history_${userId}`
    localStorage.setItem(historyKey, JSON.stringify(historyData.value))
    
    // 清空选择
    selectedHistory.value = []
    
    ElMessage.success(`成功删除 ${selectedIds.length} 条浏览记录`)
  } catch (error) {
    // 用户取消操作
  }
}

// 清空所有历史记录
const clearAllHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有浏览记录吗？此操作不可恢复！',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 清空所有历史记录
    historyData.value = []
    totalHistory.value = 0
    
    // 清空本地存储
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    const historyKey = `browse_history_${userId}`
    localStorage.removeItem(historyKey)
    
    // 清空选择
    selectedHistory.value = []
    
    ElMessage.success('所有浏览记录已清空')
  } catch (error) {
    // 用户取消操作
  }
}

// 监听类型筛选变化
watch(historyType, () => {
  console.log('类型筛选变化:', historyType.value)
  selectedHistory.value = []
  loadBrowseHistory()
})

// 组件挂载时初始化
onMounted(() => {
  loadBrowseHistory()
})
</script>

<style lang="scss" scoped>
.browse-history-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.history-card {
  border-radius: 12px;
  overflow: hidden;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.search-filter {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.history-actions {
  display: flex;
  gap: 10px;
}

.history-timeline {
  padding: 20px;
}

.history-group {
  margin-bottom: 30px;
}

.history-date {
  margin-bottom: 15px;
}

.history-date .el-divider {
  font-size: 16px;
  font-weight: 600;
  color: #4b5563;
}

.history-items {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 10px;
}

.history-title a {
  color: #409eff;
  text-decoration: none;
  &:hover {
    text-decoration: underline;
  }
}

.empty-history {
  padding: 60px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-content {
  text-align: center;
}
</style>